const express = require('express');
const db = require('../modules/DBhelper');
const moment = require('moment');

let router = express.Router();

router.post('/add', async function (request, response, next) {
    let cartObj = request.body;
    // 先查询数据库该用户是否已经购买
    let sql = 'SELECT *FROM `cart` WHERE `u_id`=? AND `c_name`=?  AND `c_size`=?';
    let pramas = [
        cartObj.uId,
        cartObj.cname,
        cartObj.csize
    ]

    let result = await db.exec(sql, pramas);

    let isAddCart = result && result.length >= 1

    if (isAddCart) {
        if (result[0].c_status == 0) {
            let sqlUpdate = 'UPDATE `cart` SET `c_size`=?,`c_num`=?,`c_price`=?,`c_total`=c_num*c_price,`c_status`=1 WHERE `u_id`=? AND `c_name`=?'

            let paramsUpdate = [
                cartObj.csize,
                cartObj.cnum,
                cartObj.cprice,
                cartObj.uId,
                cartObj.cname
            ];
            let resultUpdate = await db.exec(sqlUpdate, paramsUpdate)
            let isUpdate = resultUpdate && resultUpdate.affectedRows >= 1

            let updateMessage = {
                msg: isUpdate ? '加入购物车成功' : '加入购物车失败',
                status: isUpdate ? 200 : -200,
                model: 'update'
            }

            response.json(updateMessage);
        }else{
            let sqlUpdate = 'UPDATE `cart` SET `c_size`=?,`c_num`=c_num+?,`c_price`=?,`c_total`=c_num*c_price WHERE `u_id`=? AND `c_name`=?'

            let paramsUpdate = [
                cartObj.csize,
                cartObj.cnum,
                cartObj.cprice,
                cartObj.uId,
                cartObj.cname
            ];
            let resultUpdate = await db.exec(sqlUpdate, paramsUpdate)
            let isUpdate = resultUpdate && resultUpdate.affectedRows >= 1
    
            let updateMessage = {
                msg: isUpdate ? '加入购物车成功' : '加入购物车失败',
                status: isUpdate ? 200 : -200,
                model: 'update'
            }
    
            response.json(updateMessage);
        }
        
    } else {
        let sqlInert = 'INSERT INTO `cart` (`u_id`,`c_name`,`c_price`,`c_num`,`c_total`,`c_img`,`c_size`,`c_createtime`) VALUES (?,?,?,?,?,?,?,?)'

        let paramsInsert = [
            cartObj.uId,
            cartObj.cname,
            cartObj.cprice,
            cartObj.cnum,
            cartObj.cnum * cartObj.cprice,
            cartObj.cimgsrc,
            cartObj.csize,
            moment().format('YYYY-MM-DD HH:mm:ss')
        ]

        let resultInsert = await db.exec(sqlInert, paramsInsert)
        let isInsert = resultInsert && resultInsert.affectedRows >= 1

        let updateMessage = {
            msg: isInsert ? "加入购物车成功" : "加入购物车失败",
            status: isInsert ? 200 : -200,
            model: "insert"
        }
        response.json(updateMessage)
    }



})


//购物车页面查询购物车数据
router.get('/query', async function (request, response, next) {
    try {
        let userId = request.query.uId;
        let sql = ' SELECT *FROM cart WHERE `u_id`=? AND `c_status`=1';
        let resultQuery = await db.exec(sql, [userId]);

        response.json({
            msg: '查询成功',
            status: 200,
            data: resultQuery
        })
    } catch (error) {
        response.json({
            msg: '查询失败',
            status: -200,
            error
        })
    }
})


//购物车产品操作
router.post('/modify', async function (request, response, next) {
    try {
        let sql = 'UPDATE `cart` SET `c_num`=? ,`c_total`=c_num*`c_price` WHERE `c_id`=? ;';

        let pramas = [
            request.body.cnum,
            request.body.cId
        ]

        let result = await db.exec(sql, pramas)
        let isModify = result && result.affectedRows >= 1;
        response.json({
            msg: isModify ? "修改成功" : "修改失败",
            status: isModify ? 200 : -200
        })
    } catch (error) {
        response.json({
            msg: '修改失败'
        })
    }
})



//购物车删除
router.post("/delete", async function (request, response, next) {
    try {
        let params = [
            request.body.cId
        ]
        //软删除,其实就是修改,不是物理删除(delete...)
        let sql = " UPDATE `cart` SET `c_status`=0 WHERE c_id=? ;";

        let result = await db.exec(sql, params)

        let isDelete = result && result.affectedRows >= 1;

        response.json({
            msg: isDelete ? "删除成功" : "删除失败",
            status: isDelete ? 200 : -200
        })
    } catch (error) {
        response.json({
            msg: "删除失败",
            status: -200,
            error
        })
    }

})







module.exports = {
    router
}